﻿/*
 * Program.cs
 * 
 * 人脸录入
 * 
 * By developer_ken
 */
using OpenCvSharp;
using SmGateDemo;
using System;
using System.IO;
using System.Threading;

namespace FacePrepare
{
    class Program
    {
        static void Main(string[] args)
        {
            Camera cam = new Camera();
            FaceRecognition rec = new FaceRecognition(double.MaxValue);
            bool init = true;
            while (true)
            {
                Console.WriteLine("准备采集人脸信息");
                Console.Write("输入姓名>");
                string name = Console.ReadLine();
                bool pic = false;
                if (name.Contains("[pic]"))
                {
                    pic = true;
                    name = name.Replace("[pic]", "");
                }
                if (!pic && init)
                {
                    cam.Init();
                    init = !init;
                }
                for (int i = 0; i <= 4; i++)
                {
                    Mat frame;
                    if (!pic) frame = cam.GetLatestFrame();//拍摄一帧
                    else
                    {
                        string path = Console.ReadLine();
                        var bytes = File.ReadAllBytes(path);
                        frame = Mat.FromImageData(bytes);
                    }
                    var faces = rec.GetFacePictures(frame);//截取出人脸
                    if (faces.Length != 1)//没脸或者有好几个
                    {
                        Console.WriteLine("[Frame] 无效帧");
                        Thread.Sleep(500);
                        i--;
                        continue;
                    }
                    var validface = FaceRecognition.PreProcessFrame(faces[0]);
                    Console.WriteLine("[Frame] Quality=" + Camera.QualityRate(validface));//计算这帧照片的清晰度
                    validface.SaveImage("./known/" + name + "_" + i + ".png");//储存截取的人脸
                    Thread.Sleep(500);
                }
                Console.Write("采集完成");
            }
        }
    }
}
